importjava.util.logging.*;publicclassUserController{privatestaticfinalLoggerLOGGER=Logger.getLogger(UserController.class.getName());publicvoidloginUser(Stringusername,Stringpassword){// Perform login logicLOGGER.info("User logged in - username: "+username);}}
✅ compliance
importjava.util.logging.*;publicclassUserController{privatestaticfinalLoggerLOGGER=Logger.getLogger(UserController.class.getName());publicvoidloginUser(Stringusername,Stringpassword){// Perform login logicLOGGER.info("User logged in - username: "+obfuscateUsername(username));}privateStringobfuscateUsername(Stringusername){// Implement a method to obfuscate or mask the username// Example: Replace characters with asterisks or hash the username// ...returnusername;// Return the obfuscated username}}
Insertion of Sensitive Information Into Sent Data
🐞 non-compliance
importjava.net.HttpURLConnection;importjava.net.URL;importjava.io.OutputStream;importjava.io.IOException;publicclassPaymentService{privatestaticfinalStringAPI_ENDPOINT="https://api.example.com/payments";publicvoidmakePayment(StringcardNumber,doubleamount){try{// Create a connection to the API endpointURLurl=newURL(API_ENDPOINT);HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();connection.setRequestMethod("POST");// Set the request headersconnection.setRequestProperty("Content-Type","application/json");// Construct the request bodyStringrequestBody="{\"cardNumber\": \""+cardNumber+"\", \"amount\": "+amount+"}";// Send the requestconnection.setDoOutput(true);OutputStreamoutputStream=connection.getOutputStream();outputStream.write(requestBody.getBytes());outputStream.flush();outputStream.close();// Process the response...}catch(IOExceptione){e.printStackTrace();}}}
✅ compliance
importjava.net.HttpURLConnection;importjava.net.URL;importjava.io.OutputStream;importjava.io.IOException;publicclassPaymentService{privatestaticfinalStringAPI_ENDPOINT="https://api.example.com/payments";publicvoidmakePayment(StringcardNumber,doubleamount){try{// Create a connection to the API endpointURLurl=newURL(API_ENDPOINT);HttpURLConnectionconnection=(HttpURLConnection)url.openConnection();connection.setRequestMethod("POST");// Set the request headersconnection.setRequestProperty("Content-Type","application/json");// Construct the request body using a JSON library or object mappingJsonObjectrequestBody=newJsonObject();requestBody.addProperty("cardNumber",obfuscateCardNumber(cardNumber));requestBody.addProperty("amount",amount);// Send the requestconnection.setDoOutput(true);OutputStreamoutputStream=connection.getOutputStream();outputStream.write(requestBody.toString().getBytes());outputStream.flush();outputStream.close();// Process the response...}catch(IOExceptione){e.printStackTrace();}}privateStringobfuscateCardNumber(StringcardNumber){// Implement a method to obfuscate or mask the card number// Example: Replace characters with asterisks, mask certain digits, or encrypt the card number// ...returncardNumber;// Return the obfuscated card number}}
Cross-Site Request Forgery (CSRF)
🐞 non-compliance
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;publicclassAccountService{publicvoidupdateEmail(HttpServletRequestrequest,HttpServletResponseresponse){StringnewEmail=request.getParameter("email");// Code to update the email address in the user's account...// ...}}
✅ compliance
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importjava.util.UUID;publicclassAccountService{privatestaticfinalStringCSRF_TOKEN_SESSION_ATTR="csrfToken";publicvoidupdateEmail(HttpServletRequestrequest,HttpServletResponseresponse){StringnewEmail=request.getParameter("email");// Validate CSRF tokenHttpSessionsession=request.getSession();StringcsrfToken=(String)session.getAttribute(CSRF_TOKEN_SESSION_ATTR);StringrequestCsrfToken=request.getParameter("csrfToken");if(csrfToken==null||!csrfToken.equals(requestCsrfToken)){response.setStatus(HttpServletResponse.SC_FORBIDDEN);return;}// Code to update the email address in the user's account...// ...}publicvoidgenerateCsrfToken(HttpServletRequestrequest){HttpSessionsession=request.getSession();StringcsrfToken=UUID.randomUUID().toString();session.setAttribute(CSRF_TOKEN_SESSION_ATTR,csrfToken);}}
Use of Hard-coded Password
🐞 non-compliance
publicclassDatabaseConnection{privatestaticfinalStringDB_URL="jdbc:mysql://localhost:3306/mydatabase";privatestaticfinalStringDB_USERNAME="root";privatestaticfinalStringDB_PASSWORD="password123";publicvoidconnect(){// Code to establish a database connection using the hard-coded credentials// ...}}
✅ compliance
publicclassDatabaseConnection{privatestaticfinalStringDB_URL="jdbc:mysql://localhost:3306/mydatabase";privatestaticfinalStringDB_USERNAME="root";privateStringdbPassword;publicDatabaseConnection(StringdbPassword){this.dbPassword=dbPassword;}publicvoidconnect(){// Code to establish a database connection using the provided password// ...}}
publicclassXssExample{publicstaticStringgetUserInput(){// Assume user input is obtained from an untrusted sourceStringuserInput="<script>alert('XSS');</script>";returnuserInput;}publicstaticStringdisplayUserInput(StringuserInput){Stringhtml="<div>"+userInput+"</div>";returnhtml;}publicstaticvoidmain(String[]args){StringuserInput=getUserInput();Stringhtml=displayUserInput(userInput);System.out.println(html);}}
✅ compliance
importorg.apache.commons.text.StringEscapeUtils;publicclassXssExample{publicstaticStringgetUserInput(){// Assume user input is obtained from an untrusted sourceStringuserInput="<script>alert('XSS');</script>";returnuserInput;}publicstaticStringdisplayUserInput(StringuserInput){StringsanitizedInput=StringEscapeUtils.escapeHtml4(userInput);Stringhtml="<div>"+sanitizedInput+"</div>";returnhtml;}publicstaticvoidmain(String[]args){StringuserInput=getUserInput();Stringhtml=displayUserInput(userInput);System.out.println(html);}}
SQL Injection
🐞 non-compliance
importjava.sql.Connection;importjava.sql.ResultSet;importjava.sql.Statement;publicclassSqlInjectionExample{publicstaticvoidmain(String[]args){Stringusername="admin'; DROP TABLE users;--";Stringpassword="password";Stringquery="SELECT * FROM users WHERE username='"+username+"' AND password='"+password+"'";try{Connectionconnection=Database.getConnection();Statementstatement=connection.createStatement();ResultSetresultSet=statement.executeQuery(query);// Process the result set...}catch(Exceptione){e.printStackTrace();}}}
✅ compliance
importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;publicclassSqlInjectionExample{publicstaticvoidmain(String[]args){Stringusername="admin'; DROP TABLE users;--";Stringpassword="password";Stringquery="SELECT * FROM users WHERE username=? AND password=?";try{Connectionconnection=Database.getConnection();PreparedStatementstatement=connection.prepareStatement(query);statement.setString(1,username);statement.setString(2,password);ResultSetresultSet=statement.executeQuery();// Process the result set...}catch(Exceptione){e.printStackTrace();}}}
External Control of File Name or Path
🐞 non-compliance
importjava.io.File;publicclassFileUploadExample{publicstaticvoidmain(String[]args){StringfileName=getFileNameFromUserInput();Stringdirectory="uploads/";Filefile=newFile(directory+fileName);// Process the uploaded file...}privatestaticStringgetFileNameFromUserInput(){// Code to get file name from user input// This could be from a user input field, request parameter, etc.returnuserInput;}}
✅ compliance
importjava.io.File;importjava.nio.file.Path;importjava.nio.file.Paths;publicclassFileUploadExample{privatestaticfinalStringUPLOAD_DIRECTORY="uploads/";publicstaticvoidmain(String[]args){StringfileName=getFileNameFromUserInput();PathfilePath=Paths.get(UPLOAD_DIRECTORY,fileName).normalize();if(!filePath.startsWith(UPLOAD_DIRECTORY)){// Invalid file name or path, handle the errorreturn;}Filefile=filePath.toFile();// Process the uploaded file...}privatestaticStringgetFileNameFromUserInput(){// Code to get file name from user input// This could be from a user input field, request parameter, etc.returnuserInput;}}
Generation of Error Message Containing Sensitive Information
🐞 non-compliance
publicclassUserService{publicUsergetUserById(StringuserId){try{// Code to fetch user details from the database using the provided userId// ...}catch(Exceptione){StringerrorMessage="An error occurred while fetching user details for userId: "+userId;thrownewRuntimeException(errorMessage,e);}}}
✅ compliance
publicclassUserService{publicUsergetUserById(StringuserId){try{// Code to fetch user details from the database using the provided userId// ...}catch(Exceptione){thrownewRuntimeException("An error occurred while fetching user details",e);}}}
unprotected storage of credentials
🐞 non-compliance
publicclassUserService{privateStringusername;privateStringpassword;publicvoidlogin(Stringusername,Stringpassword){this.username=username;this.password=password;// Code to authenticate the user// ...}publicvoidprintCredentials(){System.out.println("Username: "+username);System.out.println("Password: "+password);}}
✅ compliance
publicclassUserService{privatechar[]password;publicvoidlogin(Stringusername,char[]password){// Code to authenticate the user// ...// Store the password securelythis.password=Arrays.copyOf(password,password.length);// Clear the original password dataArrays.fill(password,' ');}publicvoidprintCredentials(){System.out.println("Username: "+getUsername());System.out.println("Password: ********");}privateStringgetUsername(){// Retrieve the username from the authenticated user session// ...}}
Trust Boundary Violation
🐞 non-compliance
publicclassUserAuthenticator{privatebooleanisAdmin;publicbooleanauthenticateUser(Stringusername,Stringpassword){// Code to authenticate the user credentials// ...// Set isAdmin flag based on the authentication resultif(username.equals("admin")&&password.equals("admin123")){isAdmin=true;}returntrue;}publicvoidperformAdminAction(){if(isAdmin){// Code to perform administrative action// ...}else{System.out.println("Access denied. You are not authorized to perform this action.");}}}
✅ compliance
publicclassUserAuthenticator{privatebooleanisAdmin;publicbooleanauthenticateUser(Stringusername,Stringpassword){// Code to authenticate the user credentials// ...// Set isAdmin flag based on the authentication resultif(username.equals("admin")&&password.equals("admin123")){isAdmin=true;}else{isAdmin=false;}returntrue;}publicvoidperformAdminAction(){if(checkAdminStatus()){// Code to perform administrative action// ...}else{System.out.println("Access denied. You are not authorized to perform this action.");}}privatebooleancheckAdminStatus(){// Code to check the isAdmin flag from the authenticated user session// ...returnisAdmin;}}
Insufficiently Protected Credentials
🐞 non-compliance
publicclassUserAuthenticator{publicbooleanauthenticateUser(Stringusername,Stringpassword){// Code to authenticate the user credentials// ...// Log the username and passwordSystem.out.println("User credentials: "+username+", "+password);// Continue with authentication logic// ...returntrue;}}
✅ compliance
publicclassUserAuthenticator{publicbooleanauthenticateUser(Stringusername,Stringpassword){// Code to authenticate the user credentials// ...// Log a generic message instead of the credentialsSystem.out.println("User authentication attempt");// Continue with authentication logic// ...returntrue;}}
Improper Validation of Certificate with Host Mismatch
🐞 non-compliance
importjavax.net.ssl.HttpsURLConnection;importjava.io.IOException;importjava.net.URL;publicclassHttpClient{publicstaticvoidsendRequest(Stringurl)throwsIOException{URLrequestUrl=newURL(url);HttpsURLConnectionconnection=(HttpsURLConnection)requestUrl.openConnection();connection.setHostnameVerifier((hostname,session)->true);// Disabling hostname verificationconnection.setRequestMethod("GET");intresponseCode=connection.getResponseCode();// Process the response...}}
✅ compliance
importjavax.net.ssl.HttpsURLConnection;importjavax.net.ssl.SSLPeerUnverifiedException;importjavax.net.ssl.SSLSession;importjava.io.IOException;importjava.net.URL;publicclassHttpClient{publicstaticvoidsendRequest(Stringurl)throwsIOException{URLrequestUrl=newURL(url);HttpsURLConnectionconnection=(HttpsURLConnection)requestUrl.openConnection();connection.setRequestMethod("GET");try{connection.connect();SSLSessionsession=connection.getSSLSession();StringpeerHost=session.getPeerHost();if(!requestUrl.getHost().equals(peerHost)){thrownewSSLPeerUnverifiedException("Certificate does not match the host name");}}catch(SSLPeerUnverifiedExceptione){// Handle certificate validation failure}finally{connection.disconnect();}intresponseCode=connection.getResponseCode();// Process the response...}}
importjava.util.Scanner;importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;publicclassAuthenticationExample{privatestaticfinalStringSALT="random_salt";publicstaticvoidmain(String[]args){Scannerscanner=newScanner(System.in);System.out.print("Enter username: ");Stringusername=scanner.nextLine();System.out.print("Enter password: ");Stringpassword=scanner.nextLine();if(authenticate(username,password)){System.out.println("Authentication successful");// Proceed with privileged operation}else{System.out.println("Authentication failed");// Handle authentication failure}}privatestaticbooleanauthenticate(Stringusername,Stringpassword){// Retrieve hashed password from a secure database or storageStringstoredPasswordHash=getStoredPasswordHash(username);// Hash the input password with a saltStringhashedPassword=hashPassword(password);// Compare the stored hashed password with the input hashed passwordreturnstoredPasswordHash.equals(hashedPassword);}privatestaticStringhashPassword(Stringpassword){try{MessageDigestmessageDigest=MessageDigest.getInstance("SHA-256");messageDigest.update((password+SALT).getBytes());byte[]hashedBytes=messageDigest.digest();returnbytesToHexString(hashedBytes);}catch(NoSuchAlgorithmExceptione){// Handle the exceptione.printStackTrace();}returnnull;}privatestaticStringbytesToHexString(byte[]bytes){StringBuilderstringBuilder=newStringBuilder();for(byteb:bytes){stringBuilder.append(String.format("%02x",b));}returnstringBuilder.toString();}privatestaticStringgetStoredPasswordHash(Stringusername){// Retrieve the hashed password from a secure database or storage// based on the given username// Return the stored password hashreturn"stored_password_hash";}}
Session Fixation
🐞 non-compliance
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;publicclassSessionFixationExample{publicstaticvoidlogin(HttpServletRequestrequest,Stringusername){HttpSessionsession=request.getSession(true);session.setAttribute("username",username);}publicstaticvoidmain(String[]args){HttpServletRequestrequest=// Obtain the request objectStringusername="admin";login(request,username);// Proceed with authenticated actions}}
✅ compliance
importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;publicclassSessionFixationExample{publicstaticvoidlogin(HttpServletRequestrequest,Stringusername){HttpSessionsession=request.getSession();session.invalidate();// Invalidate the existing sessionsession=request.getSession(true);// Create a new sessionsession.setAttribute("username",username);}publicstaticvoidmain(String[]args){HttpServletRequestrequest=// Obtain the request objectStringusername="admin";login(request,username);// Proceed with authenticated actions}}
Inclusion of Functionality from Untrusted Control
🐞 non-compliance
importjava.io.File;importjava.io.IOException;publicclassUntrustedFunctionalityExample{publicstaticvoidprocessFile(Stringfilename){try{Filefile=newFile(filename);// Process the file contents}catch(IOExceptione){// Handle file processing error}}publicstaticvoidmain(String[]args){StringuserProvidedFilename="userfile.txt";processFile(userProvidedFilename);}}
✅ compliance
importjava.io.File;importjava.io.IOException;publicclassUntrustedFunctionalityExample{publicstaticvoidprocessFile(Stringfilename){// Validate and sanitize the filename before processingif(isValidFilename(filename)){try{Filefile=newFile(filename);// Process the file contents}catch(IOExceptione){// Handle file processing error}}else{// Handle invalid filename}}publicstaticbooleanisValidFilename(Stringfilename){// Implement validation logic to ensure the filename is safe// e.g., restrict file path, disallow certain characters, etc.returntrue;}publicstaticvoidmain(String[]args){StringuserProvidedFilename="userfile.txt";processFile(userProvidedFilename);}}
importjava.io.IOException;importjava.net.URL;importjava.nio.file.Files;importjava.nio.file.Path;importjava.nio.file.StandardCopyOption;importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;publicclassCodeDownloadExample{publicstaticvoiddownloadCode(Stringurl,Stringdestination){try{URLcodeUrl=newURL(url);PathdestinationPath=Path.of(destination);// Download the code to a temporary filePathtempPath=Files.createTempFile("downloaded_code",".tmp");Files.copy(codeUrl.openStream(),tempPath,StandardCopyOption.REPLACE_EXISTING);// Calculate the checksum of the downloaded codeStringchecksum=calculateChecksum(tempPath);// Verify the integrity of the downloaded codeif(isValidChecksum(checksum)){// Move the downloaded code to the destination pathFiles.move(tempPath,destinationPath,StandardCopyOption.REPLACE_EXISTING);}else{// Handle integrity check failureFiles.deleteIfExists(tempPath);}}catch(IOExceptione){// Handle download error}}publicstaticStringcalculateChecksum(PathfilePath)throwsIOException{try{MessageDigestmd=MessageDigest.getInstance("SHA-256");byte[]fileBytes=Files.readAllBytes(filePath);byte[]checksumBytes=md.digest(fileBytes);StringBuilderchecksumBuilder=newStringBuilder();for(byteb:checksumBytes){checksumBuilder.append(String.format("%02x",b));}returnchecksumBuilder.toString();}catch(NoSuchAlgorithmExceptione){thrownewRuntimeException("Error calculating checksum.",e);}}publicstaticbooleanisValidChecksum(Stringchecksum){// Compare the calculated checksum with a trusted valueStringtrustedChecksum="e1a7a76c51a1024193a54f95e3dbaeaeaa01a7544c24404db4c24bdf8a34937e";returntrustedChecksum.equals(checksum);}publicstaticvoidmain(String[]args){StringcodeUrl="http://example.com/malicious-code.jar";StringdestinationPath="/path/to/save/malicious-code.jar";downloadCode(codeUrl,destinationPath);}}
Deserialization of Untrusted Data
🐞 non-compliance
importjava.io.FileInputStream;importjava.io.IOException;importjava.io.ObjectInputStream;publicclassDeserializationExample{publicstaticvoidmain(String[]args){StringserializedData="serialized_data.ser";try(FileInputStreamfileIn=newFileInputStream(serializedData);ObjectInputStreamin=newObjectInputStream(fileIn)){Objectobj=in.readObject();// Process the deserialized object}catch(IOException|ClassNotFoundExceptione){// Handle deserialization error}}}
✅ compliance
importjava.io.FileInputStream;importjava.io.IOException;importjava.io.ObjectInputStream;publicclassDeserializationExample{publicstaticvoidmain(String[]args){StringserializedData="serialized_data.ser";try(FileInputStreamfileIn=newFileInputStream(serializedData);ObjectInputStreamin=newObjectInputStream(fileIn)){// Perform validation on the deserialized objectObjectobj=in.readObject();if(isValidObject(obj)){// Process the deserialized object}else{// Handle invalid or malicious object}}catch(IOException|ClassNotFoundExceptione){// Handle deserialization error}}publicstaticbooleanisValidObject(Objectobj){// Implement validation logic based on the expected object type// and any additional validation criteria// Example: Ensure the deserialized object is of the expected typereturnobjinstanceofMySerializableClass;}}
Insufficient Logging
🐞 non-compliance
publicclassPaymentService{privatestaticfinalLoggerlogger=Logger.getLogger(PaymentService.class.getName());publicvoidprocessPayment(StringpaymentData){// Process the payment// ...// Log the payment resultlogger.info("Payment processed successfully");}}
✅ compliance
publicclassPaymentService{privatestaticfinalLoggerlogger=Logger.getLogger(PaymentService.class.getName());publicvoidprocessPayment(StringpaymentData,Useruser){// Process the payment// ...// Log the payment result with relevant informationlogger.info("Payment processed successfully. User: "+user.getUsername()+", Amount: "+paymentData.getAmount());}}
Improper Output Neutralization for Logs
🐞 non-compliance
publicclassLoginService{privatestaticfinalLoggerlogger=Logger.getLogger(LoginService.class.getName());publicvoidlogInvalidLogin(Stringusername){// Log the invalid login attemptlogger.info("Invalid login attempt: "+username);}}
✅ compliance
publicclassLoginService{privatestaticfinalLoggerlogger=Logger.getLogger(LoginService.class.getName());publicvoidlogInvalidLogin(Stringusername){// Sanitize the username to prevent log injectionStringsanitizedUsername=sanitize(username);// Log the invalid login attempt with the sanitized usernamelogger.info("Invalid login attempt: "+sanitizedUsername);}privateStringsanitize(Stringinput){// Implement appropriate sanitization logic// ...returninput.replaceAll("[^a-zA-Z0-9]","");}}
Omission of Security-relevant Information
🐞 non-compliance
publicclassPaymentService{publicvoidprocessPayment(StringcreditCardNumber,doubleamount){// Process the payment// Log the payment without including security-relevant informationLogger.getLogger(PaymentService.class.getName()).info("Payment processed");}}
✅ compliance
publicclassPaymentService{publicvoidprocessPayment(StringcreditCardNumber,doubleamount){// Process the payment// Log the payment with security-relevant informationLoggerlogger=Logger.getLogger(PaymentService.class.getName());logger.info("Payment processed - Credit Card: "+maskCreditCardNumber(creditCardNumber)+", Amount: "+amount);}privateStringmaskCreditCardNumber(StringcreditCardNumber){// Mask the credit card number for security purposes// ...return"************"+creditCardNumber.substring(creditCardNumber.length()-4);}}
Sensitive Information into Log File
🐞 non-compliance
publicclassUserService{privatestaticfinalLoggerlogger=Logger.getLogger(UserService.class.getName());publicvoidcreateUser(Stringusername,Stringpassword){// Create the user// Log the sensitive informationlogger.info("User created - Username: "+username+", Password: "+password);}}
✅ compliance
publicclassUserService{privatestaticfinalLoggerlogger=Logger.getLogger(UserService.class.getName());publicvoidcreateUser(Stringusername,Stringpassword){// Create the user// Log a message without sensitive informationlogger.info("User created - Username: "+username);}}
Server-Side Request Forgery (SSRF)
🐞 non-compliance
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.URL;publicclassImageProcessor{publicvoidprocessImage(StringimageUrl)throwsIOException{// Retrieve image from the provided URLURLurl=newURL(imageUrl);BufferedReaderreader=newBufferedReader(newInputStreamReader(url.openStream()));// Process the image// ...}}
✅ compliance
importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.URL;publicclassImageProcessor{privatestaticfinalStringALLOWED_DOMAIN="example.com";publicvoidprocessImage(StringimageUrl)throwsIOException{// Validate the URLURLurl=newURL(imageUrl);Stringhost=url.getHost();if(!host.endsWith(ALLOWED_DOMAIN)){thrownewIllegalArgumentException("Invalid image URL");}// Retrieve image from the provided URLBufferedReaderreader=newBufferedReader(newInputStreamReader(url.openStream()));// Process the image// ...}}